package com.hf.eagle.utils;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;

import com.hf.eagle.web.base.SysConstant;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.jimi.core.JimiException;

public class StringTest {
    private int type_id;
    private int type_value;
    private Map<String,String> typeMap=new HashMap<String,String>();//key 名称  value type_value;
    private int pro_id;
    private int acc_id;
    private int acc_rel_id;
    
	public int getType_value() {
		return type_value;
	}

	public void setType_value(int type_value) {
		this.type_value = type_value;
	}

	public Map<String, String> getTypeMap() {
		return typeMap;
	}

	public void setTypeMap(Map<String, String> typeMap) {
		this.typeMap = typeMap;
	}

	public StringTest(int type_id, int type_value,
			int pro_id, int acc_id, int acc_rel_id) {
		super();
		this.type_id = type_id;
		this.type_value = type_value;
		this.pro_id = pro_id;
		this.acc_id = acc_id;
		this.acc_rel_id = acc_rel_id;
	}

	public int getType_id() {
		return type_id;
	}

	public void setType_id(int type_id) {
		this.type_id = type_id;
	}

	public int getPro_id() {
		return pro_id;
	}

	public void setPro_id(int pro_id) {
		this.pro_id = pro_id;
	}

	public int getAcc_id() {
		return acc_id;
	}

	public void setAcc_id(int acc_id) {
		this.acc_id = acc_id;
	}

	public int getAcc_rel_id() {
		return acc_rel_id;
	}

	public void setAcc_rel_id(int acc_rel_id) {
		this.acc_rel_id = acc_rel_id;
	}

	/**
	 * @param args
	 * @throws JimiException 
	 */
	public static void main(String[] args) throws JimiException {
		StringTest st=new StringTest(100, 100, 100, 500, 500);
		for (int i = 1; i <1024; i++) {
			parse(i,st);
		}
		
        //readByBytes("");
	}
	
	public static void parse(int index,StringTest st) throws JimiException{
		try{  
            URL url = new URL("http://www.eagleceramics.com/PrdShow.aspx?id="+index);
            InputStream inputstream = url.openStream(); 
            OutputStreamWriter out=new FileWriter(new File("F:\\eagle\\eagle.update.sql"),true);
            String s;  
            BufferedReader in = new BufferedReader(new  InputStreamReader(inputstream,"UTF-8"));  
            StringBuffer stringbuffer = new StringBuffer();  
            while((s = in.readLine())!=null){  
                stringbuffer.append(s);  
            }  
//            System.out.println(stringbuffer.toString());
            String htmlInfo=stringbuffer.toString();
            htmlInfo=htmlInfo.substring(htmlInfo.indexOf("首页"));
            if(htmlInfo.indexOf("title=\"")<0) return;
            //1级
            String temp1=htmlInfo.substring(htmlInfo.indexOf("title=\""));
            String temp2=temp1.substring(temp1.indexOf("\"")+1);
            String type1=temp2.substring(0, temp2.indexOf("\""));
            System.out.println("1类："+type1);
            //2级
            String temp3=temp2.substring(temp2.indexOf("title=\""));
            String temp4=temp3.substring(temp3.indexOf("\"")+1);
            String type2=temp4.substring(0, temp4.indexOf("\""));
            System.out.println("2类："+type2);
            if(!st.getTypeMap().containsKey(type1)) {
            	st.setType_value(st.getType_value()+1);
            	st.setType_id(st.getType_id()+1);
            	st.getTypeMap().put(type1,st.getType_id()+"#"+st.getType_value());
            	System.out.println("INSERT INTO `sys_dictionary` VALUES ('"+st.getType_id()+"', '0', '4000', '"+st.getType_value()+"', '"+type1+"', null, '产品一级分类', '0', '0');");
            	out.write("INSERT INTO `sys_dictionary` VALUES ('"+st.getType_id()+"', '0', '4000', '"+st.getType_value()+"', '"+type1+"', null, '产品一级分类', '0', '0');\n");
            }
            if(!st.getTypeMap().containsKey(type2)) {
            	st.setType_value(st.getType_value()+1);
            	st.setType_id(st.getType_id()+1);
            	st.getTypeMap().put(type2,st.getType_id()+"#"+st.getType_value());
            	System.out.println("INSERT INTO `sys_dictionary` VALUES ('"+st.getType_id()+"', '"+st.getTypeMap().get(type1).split("#")[0]+"', '5000', '"+st.getType_value()+"', '"+type2+"', null, '产品二级分类', '0', '0');");
            	out.write("INSERT INTO `sys_dictionary` VALUES ('"+st.getType_id()+"', '"+st.getTypeMap().get(type1).split("#")[0]+"', '5000', '"+st.getType_value()+"', '"+type2+"', null, '产品二级分类', '0', '0');\n");
            }
            
            //INSERT INTO `sys_dictionary` VALUES ('id', '0', '4000', 'i++', 'type1', null, '产品一级分类', '0', '0');
            //INSERT INTO `sys_dictionary` VALUES ('id', 'par_id', '5000', 'i++', 'type2', null, '产品二级分类', '0', '0');
            
            
            //图片地址
            String temp5=temp4.substring(temp4.indexOf("src=\""));
            String temp6=temp5.substring(temp5.indexOf("\"")+1);
            String img=temp6.substring(0, temp6.indexOf("\""));
            System.out.println(img);
            String imgName=img.substring(img.lastIndexOf("/")+1);
            System.out.println(imgName);
            //品名
            String temp7=temp6.substring(temp6.indexOf("品名:"));
            String[] temp8=temp7.substring(0,temp7.indexOf("<")).split(":");
            String pm=type2;
            if(temp8.length>1) pm=temp8[1];
            System.out.println("品名："+pm);
            
            File file3=new File("F:\\eagle\\"+type1+"\\"+type2+"\\"+pm);
            if(!file3.exists()) file3.mkdir();
            
            //型号
            String temp9=temp7.substring(temp7.indexOf("型号:"));
            String[] temp10=temp9.substring(0,temp9.indexOf("<")).split(":");
            String xh="";
            if(temp10.length>1) xh=temp10[1];
            System.out.println("型号："+xh);
            
            File file4=new File("F:\\eagle\\"+type1+"\\"+type2+"\\"+pm+"\\"+xh);
            if(!file4.exists()) file4.mkdir();
            
            //尺寸
            String temp11=temp9.substring(temp9.indexOf("尺寸:"));
            String[] temp12=temp11.substring(0,temp11.indexOf("<")).split(":");
            String cc="";
            if(temp12.length>1) cc=temp12[1];
            System.out.println("尺寸："+cc);
            String temp13=temp11.substring(temp11.indexOf("p>    <p><p>", 1)+12);
            String desc=temp13.substring(0, temp13.indexOf("<"));
            desc=desc.replaceAll("/p>", "");
            System.out.println("描述："+desc);
            System.out.println("");
            st.setPro_id(st.getPro_id()+1);
            System.out.println("INSERT INTO `product_info` VALUES ('"+st.getPro_id()+"', '"+xh+"', '"+pm+"', '"+st.getTypeMap().get(type2).split("#")[1]+"', '', '"+cc+"', null, null, null, null, null, null, null, null, '0', '0');");
            out.write("INSERT INTO `product_info` VALUES ('"+st.getPro_id()+"', '"+xh+"', '"+pm+"', '"+st.getTypeMap().get(type2).split("#")[1]+"', '', '"+cc+"', null, null, null, null, null, null, null, null, '0', '0');\n");
            //INSERT INTO `product_info` VALUES ('id', 'xh', 'pm', '上面的i++', '', '', null, null, null, null, null, null, null, null, '0', '0');
            in.close(); 
            readByBytes(type1,type2,pm,xh,cc,img,imgName,desc,st,out);
            out.close();
        }catch(IOException e){  
            e.printStackTrace();  
        }  
	}
	
	public void readByChars(String host){
		try{  
            URL url = new URL(host);
            InputStream inputstream = url.openStream();  
            String s;  
            BufferedReader in = new BufferedReader(new  InputStreamReader(inputstream,"UTF-8"));  
            StringBuffer stringbuffer = new StringBuffer();  
            while((s = in.readLine())!=null){  
                stringbuffer.append(s);  
            }  
            in.close();  
        }catch(IOException e){  
            e.printStackTrace();  
        }  
	}
	
	public static void readByBytes(String type1 ,String type2,String pm,String xh,String cc,String img,String imgName,String desc,StringTest st,OutputStreamWriter out) throws IOException, JimiException{
		//第一个
		//product_dtimg fL
		//<img src=
		//<p>品名:米开朗琪罗</p>
		//<p>型号:PE-07E</p>
		//<p>尺寸:600*600,800*800</p>
		//<p>
		//	<p>超精细喷墨、二次微晶技术，越靠近，越折服于无与伦比的细腻质感，超越天然肌理脉络，色彩幻化渐变更自然而丰富，恣意绽放。</p>
		//</p>
		//大图
		st.setAcc_id(st.getAcc_id()+1);
		System.out.println("INSERT INTO `accessory` VALUES ('"+st.getAcc_id()+"', 'big_"+imgName+"', '1', '500*500', 'files/upload/big_"+imgName+"', '"+pm+xh+"', '"+desc+"', '1', '0', '0');");
		out.write("INSERT INTO `accessory` VALUES ('"+st.getAcc_id()+"', 'big_"+imgName+"', '1', '500*500', 'files/upload/big_"+imgName+"', '"+pm+xh+"', '"+desc+"', '1', '0', '0');\n");
		st.setAcc_rel_id(st.getAcc_rel_id()+1);
		System.out.println("INSERT INTO `accessory_rel` VALUES ('"+st.getAcc_rel_id()+"', '3200', '"+st.getPro_id()+"', '"+st.getAcc_id()+"');");
		out.write("INSERT INTO `accessory_rel` VALUES ('"+st.getAcc_rel_id()+"', '3200', '"+st.getPro_id()+"', '"+st.getAcc_id()+"');\n");
		//INSERT INTO `accessory` VALUES ('id++', '图片名称.jpg', '1', '图片大小76*76', 'saveUrl', 'title', 'desc', '1', '0', '0');
		//INSERT INTO `accessory_rel` VALUES ('id++', '3200', '产品ID', '图片id');
		//小图
		st.setAcc_id(st.getAcc_id()+1);
		System.out.println("INSERT INTO `accessory` VALUES ('"+st.getAcc_id()+"', 'small_"+imgName+"', '1', '76*76', 'files/upload/small_"+imgName+"', '"+pm+xh+"', '"+desc+"', '0', '0', '0');");
		out.write("INSERT INTO `accessory` VALUES ('"+st.getAcc_id()+"', 'small_"+imgName+"', '1', '76*76', 'files/upload/small_"+imgName+"', '"+pm+xh+"', '"+desc+"', '0', '0', '0');\n");
		st.setAcc_rel_id(st.getAcc_rel_id()+1);
		System.out.println("INSERT INTO `accessory_rel` VALUES ('"+st.getAcc_rel_id()+"', '3200', '"+st.getPro_id()+"', '"+st.getAcc_id()+"');");
		out.write("INSERT INTO `accessory_rel` VALUES ('"+st.getAcc_rel_id()+"', '3200', '"+st.getPro_id()+"', '"+st.getAcc_id()+"');\n");
		//INSERT INTO `accessory` VALUES ('id++', '图片名称_small.jpg', '1', '图片大小76*76', 'files/upload/2011/10/02/_small.jpg', 'title', 'desc', '0', '0', '0');
		//INSERT INTO `accessory_rel` VALUES ('id++', '3200', '产品ID', '图片id');
		try{  
            URL url = new URL("http://www.eagleceramics.com"+img);
            InputStream inputstream = url.openStream();  
            File file=new File("F:\\eagle\\upload");
            if(!file.exists()) file.mkdirs();
            int width = SysConstant.ALBUM_VICE_IMG_SIZE[0];
			int height = SysConstant.ALBUM_VICE_IMG_SIZE[1];
			int big_width = SysConstant.ALBUM_MAIN_IMG_SIZE[0];
			int big_height = SysConstant.ALBUM_MAIN_IMG_SIZE[1];
            byte[] tempbytes = new byte[100];
            int byteread = 0;
            //读入多个字节到字节数组中，byteread为一次读入的字节数
            OutputStream outImage=new FileOutputStream(new File("F:\\eagle\\upload\\"+imgName));
            while ((byteread = inputstream.read(tempbytes)) != -1){
            	outImage.write(tempbytes);
            }
            inputstream.close();  
            outImage.close();
            st.resizeImageByFixed("F:\\eagle\\upload\\"+imgName,"F:\\eagle\\upload\\big_"+imgName,big_width,big_height);
            st.resizeImageByFixed("F:\\eagle\\upload\\"+imgName,"F:\\eagle\\upload\\small_"+imgName,width,height);
        }catch(IOException e){  
            e.printStackTrace();
        }  
	}
	
	
	public String resizeImageByFixed(String source, String desc, int width, int height) throws IOException,
	JimiException {
		Image sourceImage = ImageIO.read(new File(source));
		double sourceImageWidth = sourceImage.getWidth(null);
		double sourceImageHeight = sourceImage.getHeight(null);
		int resizedWidth = (int) sourceImageWidth;
		int resizedHeight = (int) sourceImageHeight;
		
		if (sourceImageWidth > width && sourceImageHeight > height) {
			double ratio = 0.0d;
			if (sourceImageHeight > sourceImageWidth) {
				ratio = height / sourceImageHeight;
			} else {
				ratio = width / sourceImageWidth;
			}
		
			resizedWidth = (int) (sourceImageWidth * ratio);
			resizedHeight = (int) (sourceImageHeight * ratio);
		} else if (sourceImageWidth > width && sourceImageHeight < height) {
			resizedHeight = (int) ((sourceImageHeight / sourceImageWidth) * width);
			resizedWidth = width;
		} else if (sourceImageHeight > height && sourceImageWidth < width) {
			resizedWidth = (int) ((sourceImageWidth / sourceImageHeight) * height);
			resizedHeight = height;
		} else {
			resizedWidth = (int) sourceImageWidth;
			resizedHeight = (int) sourceImageHeight;
		}
		
		if (resizedWidth > width) {
			resizedWidth = width;
		}
		if (resizedHeight > height) {
			resizedHeight = height;
		}
		
		BufferedImage bi = new BufferedImage(resizedWidth, resizedHeight, BufferedImage.TYPE_INT_RGB);
		bi.getGraphics().drawImage(sourceImage.getScaledInstance(resizedWidth, resizedHeight, Image.SCALE_SMOOTH), 0,
				0, null);
		
		FileOutputStream out = new FileOutputStream(desc);
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		encoder.encode(bi);
		out.close();
		return desc;
		}
}
